package cn.adair.xunfei;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;

import androidx.annotation.NonNull;

import com.iflytek.cloud.ErrorCode;
import com.iflytek.cloud.InitListener;
import com.iflytek.cloud.RecognizerListener;
import com.iflytek.cloud.RecognizerResult;
import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.SpeechEvent;
import com.iflytek.cloud.SpeechRecognizer;
import com.iflytek.cloud.SpeechUtility;
import com.iflytek.cloud.VoiceWakeuper;
import com.iflytek.cloud.WakeuperListener;
import com.iflytek.cloud.WakeuperResult;
import com.iflytek.cloud.util.ResourceUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.lang.ref.WeakReference;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

import io.flutter.embedding.engine.plugins.FlutterPlugin;
import io.flutter.embedding.engine.plugins.activity.ActivityAware;
import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;

public class FlutterXunfei implements FlutterPlugin, MethodChannel.MethodCallHandler, ActivityAware {
    private final static String TAG = FlutterXunfei.class.getSimpleName();

    private WeakReference<Activity> mActivity;
    private MethodChannel channel;
    // 语音识别
    private SpeechRecognizer mIat;
    // 语音唤醒对象
    private VoiceWakeuper mIvw;

    @Override
    public void onAttachedToEngine(@NonNull FlutterPluginBinding flutterPluginBinding) {
        channel = new MethodChannel(flutterPluginBinding.getBinaryMessenger(), "flutterXunfei");
        channel.setMethodCallHandler(this);
    }

    @Override
    public void onDetachedFromEngine(@NonNull FlutterPluginBinding binding) {
        channel.setMethodCallHandler(null);
        if (null != mIat) {
            // 退出时释放连接
            mIat.cancel();
            mIat.destroy();
        }
    }

    @Override
    public void onMethodCall(@NonNull MethodCall call, @NonNull MethodChannel.Result result) {
        Log.e(TAG, "----------------------" + call.method);
        switch (call.method) {
            case "initIat": // 创建讯飞语音识别
                initIat(call, result);
                break;
            case "startIat": // 开始语音识别
                startIat(call, result);
                break;
            case "stopIat": // 停止语音识别
                stopIat(call, result);
                break;
            case "cancelIat": // 取消语音识别
                cancelIat(call, result);
                break;

            case "initIvw": // 创建讯飞唤醒
                initIvw(call, result);
                break;
            case "openIvw":// 开启语音唤醒
                openIvw(call, result);
                break;
            case "closeIvw":// 关闭语音唤醒
                closeIvw(call, result);
                break;
        }
    }

    /**
     * 创建语音识别，并设置参数
     */
    private void initIat(MethodCall call, final MethodChannel.Result result) {
        String APPid = call.argument("APPid");
        SpeechUtility.createUtility(mActivity.get(), "appid=" + APPid);
        mIat = SpeechRecognizer.createRecognizer(mActivity.get(), new InitListener() {
            @Override
            public void onInit(int code) {
                if (code == ErrorCode.SUCCESS) {
                    mIat.setParameter(SpeechConstant.PARAMS, null); // 清空参数
                    mIat.setParameter(SpeechConstant.ENGINE_TYPE, SpeechConstant.TYPE_CLOUD); // 设置听写引擎
                    mIat.setParameter(SpeechConstant.RESULT_TYPE, "json");// 设置返回结果格式
                    // 设置语音前端点:静音超时时间，即用户多长时间不说话则当做超时处理
                    mIat.setParameter(SpeechConstant.VAD_BOS, "4000");
                    // 设置语音后端点:后端点静音检测时间，即用户停止说话多长时间内即认为不再输入， 自动停止录音
                    // todo 这里设置 静音时长为10秒。10秒后则自动取消识别，返回结果
                    mIat.setParameter(SpeechConstant.VAD_EOS, "1800");
                    // 设置标点符号,设置为"0"返回结果无标点,设置为"1"返回结果有标点
                    mIat.setParameter(SpeechConstant.ASR_PTT, "1");
                    // 设置音频保存路径，保存音频格式支持pcm、wav，设置路径为sd卡请注意WRITE_EXTERNAL_STORAGE权限
                    //mIat.setParameter(SpeechConstant.AUDIO_FORMAT,"wav");
                    //mIat.setParameter(SpeechConstant.ASR_AUDIO_PATH, Environment.getExternalStorageDirectory()+"/msc/iat.wav");
                    Map<String, Object> object = InitResult.result(true, "初始化成功", code, "initIat");
                    channel.invokeMethod("initResult", object);
                } else {
                    Map<String, Object> object = InitResult.result(false, "初始化失败", code, "initIat");
                    channel.invokeMethod("initResult", object);
                }
            }
        });
    }

    /**
     * 开启语音识别
     */
    private void startIat(MethodCall call, final MethodChannel.Result result) {
        if (mIat == null) {
            result.error(String.valueOf(9999), "开启语音识别失败", "未初始化语音识别");
            return;
        }
        int ret = mIat.startListening(mRecognizerListener);
        if (ret != ErrorCode.SUCCESS) {
            result.error(String.valueOf(ret), "开启语音识别失败", "开启语音识别失败");
        } else {
            result.success(0);
        }
    }

    /**
     * 停止语音识别
     */
    private void stopIat(MethodCall call, MethodChannel.Result result) {
        if (mIat == null) {
            result.error(String.valueOf(9999), "开启语音识别失败", "未初始化语音识别");
            return;
        }
        mIat.stopListening();
        result.success(0);
    }

    /**
     * 取消语音识别
     */
    private void cancelIat(MethodCall call, MethodChannel.Result result) {
        if (mIat == null) {
            result.error(String.valueOf(9999), "开启语音识别失败", "未初始化语音识别");
            return;
        }
        mIat.cancel();
        result.success(0);
    }


    /**
     * 创建语音唤醒服务，并设置参数
     */
    private void initIvw(MethodCall call, final MethodChannel.Result result) {
        String APPid = call.argument("APPid");
        SpeechUtility.createUtility(mActivity.get(), "appid=" + APPid);
        mIvw = VoiceWakeuper.createWakeuper(mActivity.get(), null);
        mIvw.setParameter(SpeechConstant.IVW_THRESHOLD, "1450");// 唤醒门限值，根据资源携带的唤醒词个数按照“id:门限;id:门限”的格式传入
        mIvw.setParameter(SpeechConstant.IVW_SST, "wakeup");// 设置唤醒模式
        mIvw.setParameter(SpeechConstant.KEEP_ALIVE, "1"); // 设置持续进行唤醒
        mIvw.setParameter(SpeechConstant.IVW_NET_MODE, "0"); // 设置闭环优化网络模式
        // 设置唤醒资源路径
        final String resPath = ResourceUtil.generateResourcePath(mActivity.get(), ResourceUtil.RESOURCE_TYPE.assets, "ivw/" + APPid + ".jet");
        Log.e("initIvw", "唤醒资源路径：" + resPath);
        mIvw.setParameter(SpeechConstant.IVW_RES_PATH, resPath);
        Map<String, Object> object = InitResult.result(true, "初始化成功", 0, "initIvw");
        channel.invokeMethod("initResult", object);
        // 设置唤醒录音保存路径，保存最近一分钟的音频
//        mIvw.setParameter( SpeechConstant.IVW_AUDIO_PATH, Environment.getExternalStorageDirectory().getPath()+"/msc/ivw.wav" );
//        mIvw.setParameter( SpeechConstant.AUDIO_FORMAT, "wav" );
        // 如有需要，设置 NOTIFY_RECORD_DATA 以实时通过 onEvent 返回录音音频流字节
        //mIvw.setParameter( SpeechConstant.NOTIFY_RECORD_DATA, "1" );
        // 启动唤醒
//        mIvw.setParameter(SpeechConstant.AUDIO_SOURCE, "-1");
    }

    /**
     * 开启语音唤醒
     */
    private void openIvw(MethodCall call, final MethodChannel.Result result) {
        if (mIvw == null) {
            result.error(String.valueOf(9999), "开启语音唤醒失败", "未初始化语音唤醒");
            return;
        }
        int ret = mIvw.startListening(mWakeuperListener);
        if (ret != ErrorCode.SUCCESS) {
            result.error(String.valueOf(ret), "开启语音唤醒失败", "开启语音唤醒失败");
        } else {
            result.success(0);
        }
    }

    /**
     * 关闭语音唤醒
     */
    private void closeIvw(MethodCall call, final MethodChannel.Result result) {
        if (mIvw == null) {
            result.error(String.valueOf(9999), "关闭语音唤醒失败", "未初始化语音唤醒");
            return;
        }
        mIvw.stopListening();
        result.success(0);
    }


    private WakeuperListener mWakeuperListener = new WakeuperListener() {

        @Override
        public void onResult(WakeuperResult result) {
            Log.d(TAG, "onResult");
//            if(!"1".equalsIgnoreCase(keep_alive)) {
//                setRadioEnable(true);
//            }
            channel.invokeMethod("onIvwResult", result.getResultString());

            String resultString = "";
            try {
                String text = result.getResultString();
                JSONObject object = new JSONObject(text);
                StringBuffer buffer = new StringBuffer();
                buffer.append("【RAW】 " + text);
                buffer.append("\n");
                buffer.append("【操作类型】" + object.optString("sst"));
                buffer.append("\n");
                buffer.append("【唤醒词id】" + object.optString("id"));
                buffer.append("\n");
                buffer.append("【得分】" + object.optString("score"));
                buffer.append("\n");
                buffer.append("【前端点】" + object.optString("bos"));
                buffer.append("\n");
                buffer.append("【尾端点】" + object.optString("eos"));
                resultString = buffer.toString();
            } catch (JSONException e) {
                resultString = "结果解析出错";
                e.printStackTrace();
            }
            Log.e("WakeuperListener-a", resultString);
        }

        @Override
        public void onError(SpeechError error) {
            Log.e("WakeuperListener-b", error.getErrorCode() + "");
            Log.e("WakeuperListener-b", error.getErrorDescription());
        }

        @Override
        public void onBeginOfSpeech() {
            Log.e("WakeuperListener-d", "onBeginOfSpeech");
        }

        @Override
        public void onEvent(int eventType, int isLast, int arg2, Bundle obj) {
            Log.e("WakeuperListener-d", "onEvent");
            switch (eventType) {
                // EVENT_RECORD_DATA 事件仅在 NOTIFY_RECORD_DATA 参数值为 真 时返回
                case SpeechEvent.EVENT_RECORD_DATA:
                    final byte[] audio = obj.getByteArray(SpeechEvent.KEY_EVENT_RECORD_DATA);
                    Log.i(TAG, "ivw audio length: " + audio.length);
                    break;
            }
        }

        @Override
        public void onVolumeChanged(int volume) {
        }
    };


    private RecognizerListener mRecognizerListener = new RecognizerListener() {

        @Override
        public void onBeginOfSpeech() {
            // 此回调表示：sdk内部录音机已经准备好了，用户可以开始语音输入
        }

        @Override
        public void onError(SpeechError error) {
            // Tips：
            // 错误码：10118(您没有说话)，可能是录音机权限被禁，需要提示用户打开应用的录音权限。
            Map ret = new HashMap();
            ret.put("error", error.getPlainDescription(true));
            channel.invokeMethod("onReceiveSpeechText", ret);
        }

        @Override
        public void onEndOfSpeech() {
            // 此回调表示：检测到了语音的尾端点，已经进入识别过程，不再接受语音输入
        }

        @Override
        public void onResult(RecognizerResult results, boolean isLast) {
            Log.d(TAG, results.getResultString());
            String retString = formatResult(results);
            Map ret = new HashMap();
            ret.put("text", retString);
            ret.put("isLast", isLast);
            ret.put("type", 1);
            channel.invokeMethod("onIatResult", ret);
        }

        @Override
        public void onVolumeChanged(int volume, byte[] data) {
            Log.d(TAG, "返回音频数据：" + data.length);
        }

        @Override
        public void onEvent(int eventType, int arg1, int arg2, Bundle obj) {
            // 以下代码用于获取与云端的会话id，当业务出错时将会话id提供给技术支持人员，可用于查询会话日志，定位出错原因
            // 若使用本地能力，会话id为null
            //	if (SpeechEvent.EVENT_SESSION_ID == eventType) {
            //		String sid = obj.getString(SpeechEvent.KEY_EVENT_SESSION_ID);
            //		Log.d(TAG, "session id =" + sid);
            //	}
        }
    };

    private String formatResult(RecognizerResult results) {
        String text = JsonParser.parseIatResult(results.getResultString());

        String sn = null;
        // 读取json结果中的sn字段
        try {
            JSONObject resultJson = new JSONObject(results.getResultString());
            sn = resultJson.optString("sn");
        } catch (JSONException e) {
            e.printStackTrace();
        }

        HashMap<String, String> iatResult = new LinkedHashMap<String, String>();

        iatResult.put(sn, text);

        StringBuffer resultBuffer = new StringBuffer();
        for (String key : iatResult.keySet()) {
            resultBuffer.append(iatResult.get(key));
        }

        return resultBuffer.toString();
    }

    @Override
    public void onAttachedToActivity(ActivityPluginBinding activityPluginBinding) {
        mActivity = new WeakReference<>(activityPluginBinding.getActivity());
    }

    @Override
    public void onDetachedFromActivityForConfigChanges() {
        mActivity = null;
    }

    @Override
    public void onReattachedToActivityForConfigChanges(ActivityPluginBinding activityPluginBinding) {

    }

    @Override
    public void onDetachedFromActivity() {

    }

}
